package com.jiahui.vote.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.jiahui.vote.entity.User;
import com.jiahui.vote.entity.Vote;
import com.jiahui.vote.service.UserService;
import com.jiahui.vote.service.VoteService;

@Controller
@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    UserService userService;
    @Autowired
    VoteService voteService;

    @GetMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password) {
        boolean result = userService.login(username, password);
        if (result) {
            return "redirect:/list";
        } else {
            return "redirect:/";
        }

    }

    @GetMapping("/register")
    public String resiger(@RequestParam String username, @RequestParam String password){
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return null;
        }
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        boolean result = userService.register(user);
        if (result) {
            return "redirect:/list";
        } else {
            return "redirect:/";
        }
    }

    @GetMapping("/addvote")
    public String addVote(@RequestParam String title, @RequestParam String option,@RequestParam String option2,@RequestParam String option3,@RequestParam String option4,@RequestParam String option5,@RequestParam String option6,@RequestParam String option7){
        if(StringUtils.isEmpty(title)||StringUtils.isEmpty(option)||StringUtils.isEmpty(option2)){
            return null;
        }
        Vote vote=new Vote();
        vote.setTitle(title);
        vote.setOption(option);
        vote.setCountoption(0);
        vote.setOption2(option2);
        vote.setCountoption2(0);
        vote.setOption3(option3);
        vote.setCountoption3(0);
        vote.setOption4(option4);
        vote.setCountoption4(0);
        vote.setOption5(option5);
        vote.setCountoption5(0);
        vote.setOption6(option6);
        vote.setCountoption6(0);
        vote.setOption7(option7);
        vote.setCountoption7(0);
        vote.setAuthor("admin");
        boolean result = voteService.addVote(vote);
        if (result) {
            return "redirect:/list";
        } else {
            return "redirect:/";
        }
    }
    @DeleteMapping("/delete/{id}")
    public String addVote(@PathVariable("id") int id){

        boolean result = voteService.deleteVote(id);

        return "redirect:/list";
    }
}
